<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Models\Tag;
use App\Models\Tagtmp;
use Input;
use App\Util\Util;

class TagController extends BaseController{
	
	public function getIndex(){
		return view('tag.index');
	}
	
	//返回DataTable
	public function getDatatable(){
        $dt=array();
        $orderby = isset( $_GET[ 'order'  ] ) ? $_GET[ 'columns' ][ $_GET[ 'order' ][ 0 ][ 'column' ] ][ 'name' ] : 'pop';
        $orderdir = isset( $_GET[ 'order'  ] ) ? $_GET[ 'order' ][ 0 ][ 'dir' ] : 'asc';
        $start = Input::get('start',0);//从多少开始
        $length = Input::get('length',10);//数据长度
        $search = $_GET['search']['value'];//搜索获取前台传过来的过滤条件
        $recordsTotal = Tag::count();
        $where='1=1 ';
        if($search!=''){
            $where.='and name like "%'.$search.'%"';
        }
        $data = Tag::whereRaw($where)->select('id', 'name','pop','created_at','updated_at')->skip($start)->take($length)->orderBy($orderby,$orderdir)->get();
        $recordsFiltered=  Tag::whereRaw($where)->count();
        $datatable=array();
        // $iseditstr='';
        $isdelstr='';
        // if (\Gate::check('chkaccess', 'App\Http\Controllers\TagController@getEdit')) {
        // 	$iseditstr='<button class="btn-white btn btn-xs" onclick="location.href=\'/tag/edit/$reeditstr\'">编辑</button>';
        // }
        if (\Gate::check('chkaccess', 'App\Http\Controllers\TagController@postDel')) {
        	$isdelstr='<button class="btn-white btn btn-xs" onclick="singledel(\'/tag/del\',$redelstr);">删除</button>';
        }
        foreach ($data as $item) {
            $obj=array('<input type="checkbox" name="chk" value='.$item->id.' />',$item->id,$item->name,$item->pop,$item->created_at->format('Y-m-d H:i:s'),$item->updated_at->format('Y-m-d H:i:s'),str_replace('$redelstr',$item->id,$isdelstr));
            array_push($datatable,$obj);
        }
        $dt['draw']=intval(Input::get('draw',0));
        $dt['data']=$datatable;
        $dt['recordsTotal']=$recordsTotal;
        $dt['recordsFiltered']=$recordsFiltered;
        // $dt['error']='暂时没有数据';
        echo json_encode($dt);     
    }
    
	public function getAdd(){
		return view('tag.add');
	}

	public function postAdd(){
        \Input::merge(array_map('trim', \Input::all()));
		$name=Input::get('name');
		$tag = new Tag;
		$tag->name = $name;
		$isExist=Tag::where('name',$name)->first();
		if($isExist){
			return redirect('tooltip/failure')->with(['redirectway'=>'名称已存在，添加失败！','redirecturl'=>'/tag/index']);
		}
		$util=new Util;
        $tag->indexf = $util->getFirstCharter($name);
		$res=$tag->save();
		if($res){
			return redirect('tooltip/success')->with(['redirectway'=>'添加成功！','redirecturl'=>'/tag/index']);
		}else{
			return redirect('tooltip/failure')->with(['redirectway'=>'添加失败！','redirecturl'=>'/tag/index']);
		}
	}

    public function getBatadd(){
        return view('tag.batadd');
    }

    public function postBatadd(){
        \Input::merge(array_map('trim', \Input::all()));
        $name=Input::get('name');
        $namearr=explode(',',$name);
        foreach ($namearr as $key => $value) {
            $tag = new Tag;
            $tag->name = $value;
            $isExist=Tag::where('name',$value)->first();
            if(!$isExist){
                $util=new Util;
                $tag->indexf = $util->getFirstCharter($value);
                $res=$tag->save();            
            }
        }
        return redirect('tooltip/success')->with(['redirectway'=>'添加成功！','redirecturl'=>'/tag/index']);
       
    }
	
	public function getEdit($id){
		$info = Tag::find($id);
		return view('tag.edit')->with('info',$info);
	}

	public function postEdit(){
        \Input::merge(array_map('trim', \Input::all()));
		$tag = Tag::find(Input::get('id'));
		$tag->name = Input::get('name');
		$isExist=Tag::where('id','!=',$tag->id)->where('name',$tag->name)->first();
		if($isExist){
			return redirect('tooltip/failure')->with(['redirectway'=>'名称已存在，修改失败！','redirecturl'=>'/tag/index']);
		}
		$util=new Util;
        $tag->indexf = $util->getFirstCharter($tag->name);
		$res=$tag->save();
		if($res){
			return redirect('tooltip/success')->with(['redirectway'=>'修改成功！','redirecturl'=>'/tag/index']);
		}else{
			return redirect('tooltip/failure')->with(['redirectway'=>'修改失败！','redirecturl'=>'/tag/index']);
		}
	}

	public function postDel(){
		$res=Tag::destroy(Input::get('data'));
		if($res){
			die('1');
		}
		else{
			die('0');
		}
	}

	public function getTmpindex(){
		return view('tag.tmpindex');
	}
	
	//返回DataTable
	public function getTmpdatatable(){
        $dt=array();
        $orderby = isset( $_GET[ 'order'  ] ) ? $_GET[ 'columns' ][ $_GET[ 'order' ][ 0 ][ 'column' ] ][ 'name' ] : 'pop';
        $orderdir = isset( $_GET[ 'order'  ] ) ? $_GET[ 'order' ][ 0 ][ 'dir' ] : 'asc';
        $start = Input::get('start',0);//从多少开始
        $length = Input::get('length',10);//数据长度
        $search = $_GET['search']['value'];//搜索获取前台传过来的过滤条件
        $recordsTotal = Tagtmp::count();
        $where='1=1 ';
        if($search!=''){
            $where.='and name like "%'.$search.'%"';
        }
        $data = Tagtmp::whereRaw($where)->select('id', 'name','pop')->skip($start)->take($length)->orderBy($orderby,$orderdir)->get();
        $recordsFiltered=  Tagtmp::whereRaw($where)->count();
        $datatable=array();
        $iscolstr='';
        $isdelstr='';
        if (\Gate::check('chkaccess', 'App\Http\Controllers\TagController@postTmpcol')) {
            $iscolstr='<button class="btn-white btn btn-xs" onclick="singlecol(\'/tag/tmpcol\',$recolstr);">收藏</button>';
        }
        if (\Gate::check('chkaccess', 'App\Http\Controllers\TagController@postTmpdel')) {
        	$isdelstr='<button class="btn-white btn btn-xs" onclick="singledel(\'/tag/tmpdel\',$redelstr);">删除</button>';
        }
        foreach ($data as $item) {
            $obj=array('<input type="checkbox" name="chk" value='.$item->id.' />',$item->id,$item->name,$item->pop,str_replace('$recolstr',$item->id,$iscolstr).str_replace('$redelstr',$item->id,$isdelstr));
            array_push($datatable,$obj);
        }
        $dt['draw']=intval(Input::get('draw',0));
        $dt['data']=$datatable;
        $dt['recordsTotal']=$recordsTotal;
        $dt['recordsFiltered']=$recordsFiltered;
        // $dt['error']='暂时没有数据';
        echo json_encode($dt);     
    }
    

	public function postTmpdel(){
		$res=Tagtmp::destroy(Input::get('data'));
		if($res){
			die('1');
		}
		else{
			die('0');
		}
	}

    public function postTmpcol(){
        $data=Input::get('data');
        $res=Tagtmp::whereIn('id',$data)->get();
        foreach ($res as $key => $value) {
            $isexist=Tag::where('name',$value->name)->first();
            if($isexist){
                return redirect('tooltip/failure')->with(['redirectway'=>'名称已存在，收藏失败！','redirecturl'=>'/tag/tmpindex']);
            }else{
                Tagtmp::destroy($data);
                $tag = new Tag;
                $tag->name = $value->name;
                $util=new Util;
                $tag->indexf = $util->getFirstCharter($value->name);
                $tag->pop = $value->pop;
                $result=$tag->save();
            }
        }
        die('1');
    }

	public function getSearch(){
        $tag= \App\Models\Tag::where('name','like','%'.Input::get('q').'%')->select('id','name')->get();
        $total_count=$tag->count();
        $jsonarr['total_count']=$total_count;
        $jsonarr['incomplete_results']=false;
        $jsonarr['items']=$tag->toArray();
        $json=json_encode($jsonarr);
        die($json);

    }

}
